// 获取DOM元素
const loginForm = document.getElementById('loginForm');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const usernameError = document.getElementById('usernameError');
const passwordError = document.getElementById('passwordError');
const loginButton = document.getElementById('loginButton');
const togglePassword = document.getElementById('togglePassword');
const successModal = document.getElementById('successModal');
const errorModal = document.getElementById('errorModal');
const errorMessage = document.getElementById('errorMessage');

// 密码显示/隐藏切换
togglePassword.addEventListener('click', function() {
    const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
    passwordInput.setAttribute('type', type);
    
    // 切换图标
    const icon = this.querySelector('i');
    icon.classList.toggle('fa-eye');
    icon.classList.toggle('fa-eye-slash');
});

// 添加输入动画效果
[usernameInput, passwordInput].forEach(input => {
    input.addEventListener('focus', function() {
        this.parentElement.style.transform = 'scale(1.02)';
    });
    
    input.addEventListener('blur', function() {
        this.parentElement.style.transform = 'scale(1)';
    });
});

// 表单验证函数
function validateUsername(username) {
    if (!username.trim()) {
        return '请输入用户名';
    }
    if (username.length < 3) {
        return '用户名至少3个字符';
    }
    if (username.length > 20) {
        return '用户名最多20个字符';
    }
    if (!/^[a-zA-Z0-9_]+$/.test(username)) {
        return '用户名只能包含字母、数字和下划线';
    }
    return '';
}

function validatePassword(password) {
    if (!password) {
        return '请输入密码';
    }
    if (password.length < 6) {
        return '密码至少6个字符';
    }
    return '';
}

// 实时验证
usernameInput.addEventListener('input', function() {
    const error = validateUsername(this.value);
    usernameError.textContent = error;
    this.classList.toggle('error', !!error);
});

passwordInput.addEventListener('input', function() {
    const error = validatePassword(this.value);
    passwordError.textContent = error;
    this.classList.toggle('error', !!error);
});

// 表单提交处理
loginForm.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    // 清除之前的错误
    usernameError.textContent = '';
    passwordError.textContent = '';
    
    // 获取表单数据
    const username = usernameInput.value.trim();
    const password = passwordInput.value;
    
    // 验证表单
    const usernameValidationError = validateUsername(username);
    const passwordValidationError = validatePassword(password);
    
    if (usernameValidationError || passwordValidationError) {
        usernameError.textContent = usernameValidationError;
        passwordError.textContent = passwordValidationError;
        shakeForm();
        return;
    }
    
    // 显示加载状态
    loginButton.disabled = true;
    loginButton.querySelector('.button-text').style.display = 'none';
    loginButton.querySelector('.loading-spinner').style.display = 'block';
    
    try {
        // 模拟网络延迟
        await new Promise(resolve => setTimeout(resolve, 1500));
        
        // 发送登录请求
        const response = await fetch('http://localhost:3000/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                password: password
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // 登录成功
            showSuccessModal();
            
            // 保存token到localStorage
            localStorage.setItem('token', data.token);
            
            // 延迟跳转
            setTimeout(() => {
                window.location.href = 'dashboard.html';
            }, 2000);
            
        } else {
            // 登录失败
            showErrorModal(data.message || '登录失败，请重试');
            loginButton.disabled = false;
            loginButton.querySelector('.button-text').style.display = 'inline';
            loginButton.querySelector('.loading-spinner').style.display = 'none';
            shakeForm();
        }
        
    } catch (error) {
        console.error('登录请求失败:', error);
        showErrorModal('网络连接失败，请检查网络后重试');
        loginButton.disabled = false;
        loginButton.querySelector('.button-text').style.display = 'inline';
        loginButton.querySelector('.loading-spinner').style.display = 'none';
        shakeForm();
    }
});

// 表单抖动动画
function shakeForm() {
    loginCard = document.querySelector('.login-card');
    loginCard.style.animation = 'shake 0.5s ease-in-out';
    setTimeout(() => {
        loginCard.style.animation = '';
    }, 500);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-10px); }
        75% { transform: translateX(10px); }
    }
`;
document.head.appendChild(style);

// 显示成功模态框
function showSuccessModal() {
    successModal.style.display = 'flex';
}

// 显示错误模态框
function showErrorModal(message) {
    errorMessage.textContent = message;
    errorModal.style.display = 'flex';
}

// 关闭错误模态框
function closeErrorModal() {
    errorModal.style.display = 'none';
}

// 点击模态框外部关闭
window.addEventListener('click', function(e) {
    if (e.target === errorModal) {
        closeErrorModal();
    }
});

// 回车键提交表单
usernameInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        passwordInput.focus();
    }
});

passwordInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
        loginForm.dispatchEvent(new Event('submit'));
    }
});

// 页面加载动画
window.addEventListener('load', function() {
    document.querySelector('.login-card').style.animation = 'fadeInUp 0.6s ease-out';
});

// 添加淡入动画
const fadeInStyle = document.createElement('style');
fadeInStyle.textContent = `
    @keyframes fadeInUp {
        from {
            opacity: 0;
            transform: translateY(30px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
`;
document.head.appendChild(fadeInStyle);

// 检查是否已登录
document.addEventListener('DOMContentLoaded', function() {
    const token = localStorage.getItem('token');
    if (token) {
        // 验证token有效性
        fetch('http://localhost:3000/api/verify', {
            headers: {
                'Authorization': `Bearer ${token}`
            }
        })
        .then(response => {
            if (response.ok) {
                window.location.href = 'dashboard.html';
            } else {
                localStorage.removeItem('token');
            }
        })
        .catch(() => {
            localStorage.removeItem('token');
        });
    }
});